/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.core.service;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.aspose.cells.DateTime;
import com.jeeplus.common.utils.DbUtils;
import com.jeeplus.common.utils.XmlUtils;
import com.jeeplus.modules.sys.entity.Pagination;
import org.dom4j.Element;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.transaction.annotation.Transactional;

import com.jeeplus.core.persistence.BaseEntity;
import com.jeeplus.modules.sys.entity.DataRule;
import com.jeeplus.modules.sys.utils.UserUtils;

/**
 * Service基类
 * @author jeeplus
 * @version 2017-05-16
 */
@Transactional(readOnly = true)
public abstract class BaseService {
	@Autowired
	DbUtils dbUtils;
	/**
	 * 日志对象
	 */
	protected Logger logger = LoggerFactory.getLogger(getClass());

	
	/**
	 * 数据范围过滤
	 * @param entity 当前过滤的实体类
	 */
	public static void dataRuleFilter(BaseEntity<?> entity) {

		entity.setCurrentUser(UserUtils.getUser());
		List<DataRule> dataRuleList = UserUtils.getDataRuleList();
		
		// 如果是超级管理员，则不过滤数据
		if (dataRuleList.size() == 0) {
			return;
		}

		// 数据范围
		StringBuilder sqlString = new StringBuilder();

		
			for(DataRule dataRule : dataRuleList){
				if(entity.getClass().getSimpleName().equals(dataRule.getClassName())){
					sqlString.append(dataRule.getDataScopeSql());
				}
				
			}

		entity.setDataScope(sqlString.toString());
		
	}
	/***
	 * 获取Mapper脚本
	 *
	 * @Author LH
	 * @Description //TODO
	 * @Date 10:05 2019/11/4
	 * @param obj
	 * @param mapperName
	 * @return java.lang.String
	 **/
	public static String mapperSql(Object obj,String mapperName,String xPath,String nodeName){
		try {
			String filePath=obj.getClass().getResource("../mapper/xml/"+mapperName+".xml").getPath();
			StringBuffer sb=new StringBuffer();
			for (Element element: XmlUtils.getListNodes(filePath,"//"+xPath)){
				if(element.attribute("id").getValue().equals(nodeName)){
					for (int i=0;i<element.nodeCount();i++){
						if(element.node(i).getPath().contains("include")){
							for (Element e:XmlUtils.getChildList(element)){
								String ele=e.attribute("refid").getValue();
								for (Element e1:XmlUtils.getListNodes(filePath,"//sql")){
									if(e1.attribute("id").getValue().equals(ele)){
										sb.append(e1.getTextTrim());
									}
								}
							}
						}
						else {

							sb.append(element.node(i).getText());
						}
					}
				}
				else {
					System.out.println("未检测到节点");
				}
			}

			return sb.toString();
		}
		catch (Exception e){
			e.printStackTrace();
		}
		return "";
	}
	/***
	 * 对象转换map
	 *
	 * @Author LH
	 * @Description //TODO
	 * @Date 22:24 2019/11/4
	 * @param obj
	 * @return java.util.Map<java.lang.String,java.lang.Object>
	 **/
	public static Map<String,Object> getMap(Object obj) throws Exception {
		Map<String,Object> map=new HashMap<>();
		try {
			String className=obj.getClass().getName();
			Class<?> clz = Class.forName(className);
			Field[] fields = clz.getDeclaredFields();
			for (Field f : fields) {
				if(f.getName().equals("this$0")){
					continue;
				}
				f.setAccessible(true);
				map.put(f.getName(),f.get(obj));
			}
		}
		catch (Exception e){
			e.printStackTrace();
			throw new Exception("实例转换失败!");
		}
		return map;
	}
	/***
	 * 获取分页数据
	 *
	 * @Author LH
	 * @Description //TODO
	 * @Date 18:33 2019/11/12
	 * @param pagination
	 * @param jdbc
	 * @param sql
	 * @return com.jeeplus.modules.sys.entity.Pagination
	 **/
	public <T> Pagination findPageListLimit(Pagination pagination, JdbcTemplate jdbc, String sql) throws Exception {
		try {
			NamedParameterJdbcTemplate jdbcTemplate = new NamedParameterJdbcTemplate(jdbc);
			Map<String, Object> params = new HashMap<String, Object>();
			pagination.setRecords(jdbcTemplate.queryForObject(dbUtils.getCountString(sql), params, Integer.class));
			sql = new DbUtils().getLimitString(sql, (pagination.getPage()-1)*pagination.getRows(),pagination.getRows());
			List<Map<String,Object>> list = jdbcTemplate.queryForList(sql, params);
			pagination.setData(list);
		}
		catch (Exception e){
			e.printStackTrace();
			logger.error(e.getMessage());
			throw new Exception(e.getCause());
		}
		return pagination;
	}
}
